const Router = require('@koa/router')()
const Redis = require('../../middleware/redis')
const Sms = require('../../middleware/alicloud')
const Send = require('../../middleware/email')
const Util = require('../../util')
const jwt = require('../../middleware/jwt/jwt')
const { User, Data } = require('../schema')


Router.get('/code', async ctx => {
  const { sessionID, account, type } = ctx.query
  const verFlog = await Util.checkUndefined([
    { account, type: 'string', label: 'account' }
  ]);
  if (verFlog) {
    let flog
    if (type) {
      flog = false;
    } else {
      flog = await User.findOne({ account });
    }
    if (flog) {
      return ctx.body = Util.back(-400)
    } else {
      if (Util.regexp.email.test(account)) {
        const oldCode = await Redis.get('email' + sessionID + account)
        if (oldCode) {
          return ctx.body = Util.back(-104)
        } else {
          return ctx.body = await Send(account).then(res => {
            Redis.set('email' + sessionID + account, res.verify, 5)
            if (res.flog.messageId) {
              return {
                code: 0,
                data: '',
                msg: '验证码发送成功'
              }
            }
          })
        }
      } else if (Util.regexp.phone.test(account)) {
        const oldCode = await Redis.get('code' + sessionID + account)
        if (oldCode) {
          return ctx.body = Util.back(-104)
        } else {
          // const smscode = await Sms(account);
          const smscode = '1111'
          Redis.set('code' + sessionID + account, smscode, 3)
          return ctx.body = {
            code: 0,
            data: '',
            msg: '验证码发送成功'
          }
        }
      }
    }
  } else {
    return ctx.body = Util.back(-101)
  }
})

Router.post('/register', async ctx => {
  const { sessionID, account, password, code } = ctx.request.body
  const verFlog = await Util.checkUndefined([
    { account, type: 'string', label: 'account' },
    { password, type: 'string', label: 'password' },
    { code, type: 'string', label: 'code' }
  ]);
  if (verFlog) {
    let type = undefined
    if (Util.regexp.email.test(account)) {
      type = 'email'
    } else if (Util.regexp.phone.test(account)) {
      type = 'code'
    }
    const smscode = await Redis.get(type + sessionID + account)
    if (code === smscode) {
      const flog = await User.findOne({ account });
      if (flog) {
        return ctx.body = Util.back(-400)
      } else {
        return ctx.body = await new User({ account, password }).save().then(res => {
          Redis.del(type + sessionID + account)
          return {
            data: res.account,
            code: 0,
            msg: '注册成功'
          }
        })
      }
    } else {
      return ctx.body = Util.back(-103)
    }
  } else {
    return ctx.body = Util.back(-101)
  }
})

Router.post('/login', async ctx => {
  const { sessionID, account, password, code } = ctx.request.body

  const verFlog = await Util.checkUndefined([
    { account, type: 'string', label: 'account' }
  ]);
  if (verFlog) {
    const flog = await User.findOne({ account });
    if (flog) {
      let verPassword
      if (password) {
        verPassword = await User.findOne({ account, password });
      } else if (code) {
        verPassword = code === await Redis.get('code' + sessionID + account)
      }
      if (verPassword) {
        // const token = Jwt.sign({ _id: flog._id }, 'anlin', { expiresIn: '2h' });
        const authorization = ctx.request.header.authorization;


        let result 
        if(authorization) {
          const token = authorization.split(' ')[1]
          if(token) {
            result = await token.split('.')[0]
          }
        }
        // 设置token
        const token = jwt.sign(flog._id, Date.now(), Util.tokenTime, result)
        // 删除老的token
        

        if(code) Redis.del('code' + sessionID + account)        
        const userinfo = Object.assign({}, flog._doc)
        let userData = {}
        const hasUserData = await Data.findOne({ account })
        if (hasUserData) {
          userData = hasUserData
        } else {
          userData = await new Data({ account, qd: 0 }).save()
        }
        delete userinfo.password
        return ctx.body = {
          code: 0,
          data: {
            token: token,
            userInfo: userinfo,
            userData: userData
          },
          msg: '登录成功'
        }
      } else {
        if (password) return ctx.body = Util.back(-401)
        if (code) return ctx.body = Util.back(-103)
      }
    } else {
      return ctx.body = Util.back(-402)
    }
  } else {
    return ctx.body = Util.back(-101)
  }
})

Router.post('/password', async ctx => {
  const { sessionID, account, password, code } = ctx.request.body;
  const verFlog = await Util.checkUndefined([
    { account, type: 'string', label: 'account' },
    { password, type: 'string', label: 'password' },
    { code, type: 'string', label: 'code' }
  ]);
  if (verFlog) {
    const flog = await User.findOne({ account });
    if (flog) {
      let type = undefined
      if (Util.regexp.email.test(account)) {
        type = 'email'
      } else if (Util.regexp.phone.test(account)) {
        type = 'code'
      }
      const smscode = await Redis.get(type + sessionID + account)
      if (smscode === code) {
        const checkPassword = await User.findOne({ account, password })
        if (checkPassword) {
          return ctx.body = Util.back(-403)
        } else {
          return ctx.body = await User.updateOne({ account }, { password }).then(res => {
            Redis.del(type + sessionID + account)
            return {
              code: 0,
              data: '',
              msg: '密码修改成功'
            }
          })
        }
      } else {
        return ctx.body = Util.back(-103)
      }
    } else {
      return ctx.body = Util.back(-402)
    }
  } else {
    return ctx.body = Util.back(-101)
  }
})

module.exports = Router.routes()